package com.ljs.module.entity.template.custom;

import com.ljs.module.common.TypeEnum;
import com.ljs.module.entity.BaseEntity;
import com.ljs.module.entity.ConfigProperties;
import com.ljs.module.util.TemplateUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Custom extends BaseEntity {
    private String fileName;
    private String path;
    private String template;
    private String[] configs;

    public String build() {
        setConfigProperties(ConfigProperties.of(configs));
        Map<String, Object> templateKeyORM = TemplateUtil.getTemplateKeyORM(this);
        String render = TemplateUtil.render(TypeEnum.CUSTOM_TEMPLATE.getTemplate() + template, templateKeyORM);
        if (configProperties.isLocation()) {
            File file = new File(path + File.separator + fileName);
            if (file.exists() && !configProperties.isOverride()) {
                return file.getAbsolutePath() +  "文件已存在";
            }
            FileOutputStream fis = null;
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
                fis = new FileOutputStream(file);
                fis.write(render.getBytes("UTF-8"));
                fis.close();
                return file.getAbsolutePath() + " 添加成功";
            } catch (IOException e) {
                return file.getAbsolutePath() +  "插入失败";
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return render;
    }
}
